package factory

import (
	"context"
	"errors"
	"fmt"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"mall_admin_api/biz/handler/common"
	"os"
	"strings"
)

type UploadFactory struct {
	c *common.Response
}

func newUploadFactory(f *common.Response) *UploadFactory { return &UploadFactory{c: f} }

func (u *UploadFactory) Upload(ctx context.Context) (string, error) {
	file, err := u.c.GetRequestContext().FormFile("file")
	if err != nil {
		hlog.CtxErrorf(ctx, "upload form file failed: %v", err)
		return "", err
	}

	pwd, _ := os.Getwd()
	fileName := fmt.Sprintf("./image/%s", file.Filename)
	err = u.c.GetRequestContext().SaveUploadedFile(file, fileName)
	if err != nil {
		hlog.CtxErrorf(ctx, "upload save file failed: %v", err)
		return "", errors.New(err.Error() + "   " + pwd)
	}
	return strings.Trim(fileName, "."), nil
}

func (u *UploadFactory) PackImageURL(ctx context.Context, host string, list []string) ([]string, error) {
	for key, material := range list {
		list[key] = fmt.Sprintf("%s%s", host, material)
	}
	return list, nil
}
